package drivers

import (
	"account/configs"
	"fmt"
	"time"

	"strconv"

	"github.com/go-redis/redis"
)

var Client *redis.Client
var ClientCluster *redis.ClusterClient

// TODO Redis 队列封装
// TODO Redis 队列操作

// 初始化单节点 | 测试
func initRedisNode() {

	redisConfig := configs.GetRedisNodeConfig()
	db, _ := strconv.Atoi(redisConfig["node"]["db"])
	Client = redis.NewClient(&redis.Options{
		Addr:     redisConfig["node"]["host"],
		Password: redisConfig["node"]["password"], // no password set
		DB:       db,                              // use default DB
	})

	if _, err := Client.Ping().Result(); err != nil {
		panic(" Connection redis Failed: " + err.Error())
	}

}

// 初始化集群节点 | 默认加载集群节点
func initRedisClusterNode() {

	redisConfig := configs.GetRedisClusterConfig()

	ClientCluster = redis.NewClusterClient(&redis.ClusterOptions{
		Addrs:        redisConfig["node"]["host"].([]string),
		DialTimeout:  redisConfig["node"]["dialTimeout"].(time.Duration),
		ReadTimeout:  redisConfig["node"]["readTimeout"].(time.Duration),
		WriteTimeout: redisConfig["node"]["writeTimeout"].(time.Duration),
		PoolSize:     redisConfig["node"]["poolSize"].(int),
		MaxConnAge:   redisConfig["node"]["maxConnAge"].(time.Duration),
	})

	if _, err := ClientCluster.Ping().Result(); err != nil {
		panic(" Connection redis cluster Failed: " + err.Error())

	}
}

func init() {

	fmt.Println("MyRedis-Init")
	// test 单节点
	// initRedisNode()
	// test 集群节点
	// initRedisClusterNode()

	if configs.RedisSelectNodeOrCluster() {
		initRedisClusterNode()
	} else {
		initRedisNode()
	}
}

func MyRedisClosed() {
	if configs.RedisSelectNodeOrCluster() {
		ClientCluster.Close()
	} else {
		Client.Close()
	}
}
